package it.unibo.refolding.pico.transformers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;

import com.google.common.base.Preconditions;

public class ByteArray2ShortArrayStrategyDouble implements Transformer {
  
  private final ByteOrder byteOrder;

  public ByteArray2ShortArrayStrategyDouble(ByteOrder byteOrder) {
    this.byteOrder = byteOrder;
  }

  @Override
  public short[] transform(byte[] input, double factor) {
    Preconditions.checkArgument((input.length & 3) == 0);
    ByteBuffer bb = ByteBuffer.wrap(input);
    bb.order(byteOrder);
    DoubleBuffer fb = bb.asDoubleBuffer();
    int len = input.length >> 2;
    short[] s = new short[len];
    for (int i = 0; i < len; ++i) {
      double a = fb.get();
      double d = a / factor;
      Preconditions.checkArgument(Math.abs(d) <= Short.MAX_VALUE, d);
      s[i] = (short) d;
    }
    assert !fb.hasRemaining();
    return s;
  }
}
